<template>
  <div class="app-container">
    <!-- 顶部切换标签 -->
    <el-tabs v-model="activeTab">
      <el-tab-pane label="病历" name="medical">
        <!-- 病历表单 -->
        <el-form :model="medicalForm" ref="medicalFormRef" label-width="100px">
          <!-- 基本信息部分 -->
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="患者姓名" prop="patientName">
                <el-input v-model="medicalForm.patientName" placeholder="请输入姓名或就诊卡号/身份证号" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="患者卡号" prop="patientCard">
                <el-input v-model="medicalForm.patientCard" placeholder="请输入就诊卡号" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!-- <el-form-item label="患者性别" prop="gender">
                <el-select v-model="medicalForm.gender" placeholder="男">
                  <el-option label="男" value="0" />
                  <el-option label="女" value="1" />
                  <el-option label="未知" value="2" />
                </el-select>
              </el-form-item> -->

              <el-form-item label="患者性别">
                <span v-if="medicalForm.gender == '0'">男</span>
                <span v-else-if="medicalForm.gender == '1'">女</span>
                <span v-else>未知</span>
              </el-form-item>

            </el-col>
            <el-col :span="6">
              <el-form-item label="出生日期" prop="birthDate">
                <el-date-picker v-model="medicalForm.birthDate" type="date" placeholder="选择日期" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="6">
              <!-- <el-form-item label="性别" prop="gender">
                <el-select v-model="medicalForm.gender" placeholder="男">
                  <el-option label="男" value="male" />
                  <el-option label="女" value="female" />
                </el-select>
              </el-form-item> -->
            </el-col>
            <el-col :span="6">
              <el-form-item label="手机号码" prop="phone">
                <el-input v-model="medicalForm.phone" placeholder="请输入手机号码" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="证件号码" prop="idCard">
                <el-input v-model="medicalForm.idCard" placeholder="请输入证件号码" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="接诊类型" prop="reportType">
                <el-select v-model="medicalForm.reportType" placeholder="请选择">
                  <el-option label="初诊" value="1" />
                  <el-option label="复诊" value="2" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="地址" prop="address">
                <el-input v-model="medicalForm.address" placeholder="请输入详细地址" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 体格信息 -->
          <div class="sub-title">体格信息</div>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="体温">
                <el-input v-model="medicalForm.temperature">
                  <template #append>℃</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="呼吸">
                <el-input v-model="medicalForm.breathing">
                  <template #append>次/分</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="脉搏">
                <el-input v-model="medicalForm.pulse">
                  <template #append>次/分</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="血压">
                <el-input v-model="medicalForm.bloodPressure">
                  <template #append>mmHg</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="身高">
                <el-input v-model="medicalForm.height">
                  <template #append>℃</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="体重">
                <el-input v-model="medicalForm.weight">
                  <template #append>Kg</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="血糖">
                <el-input v-model="medicalForm.bloodSugar">
                  <template #append>mmol/l</template>
                </el-input>
      </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="血脂">
                <el-input v-model="medicalForm.bloodFat">
                  <template #append>mmol/l</template>
                </el-input>
      </el-form-item>
            </el-col>
          </el-row>

          <!-- 病历信息 -->
          <div class="sub-title">病历信息</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="发病日期" prop="onsetDate">
                <el-date-picker v-model="medicalForm.onsetDate" type="date" placeholder="选择日期" style="width: 100%" />
      </el-form-item>
            </el-col>
            <el-col :span="12">


              <!-- <el-form-item label="主诉" prop="type">
                <el-select v-model="medicalForm.mainComplaint" placeholder="请选择主诉">
                  <el-option v-for="dict in doctor_complaints_info" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item> -->
              <!-- <el-form-item label="主诉" prop="mainComplaint">
                <el-select v-model="medicalForm.mainComplaint" multiple placeholder="请选择主诉">
                  <el-option v-for="dict in doctor_complaints_info" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item> -->
              <el-form-item label="主诉" prop="mainComplaint">
                <el-select v-model="medicalForm.mainComplaint" multiple placeholder="请选择主诉" value-key="label">
                  <el-option v-for="dict in doctor_complaints_info" :key="dict.value" :label="dict.label"
                    :value="dict.label" />
                </el-select>
      </el-form-item>
              <!-- {{ medicalForm.mainComplaint }} -->

              <!-- <el-form-item label="角色">
              <el-select v-model="form.roleIds" multiple placeholder="请选择">
                <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId" :disabled="item.status == 1"></el-option>
              </el-select>
            </el-form-item> -->

            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <!-- <el-form-item label="现病史" prop="presentIllness">
                <el-select v-model="medicalForm.presentIllness" multiple placeholder="请选择" style="width: 100%">
                  <el-option v-for="item in presentIllnessOptions" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item> -->

              <el-form-item label="现病史" prop="presentIllness">
                <el-select v-model="medicalForm.presentIllness" multiple placeholder="请选择现病史" value-key="label">
                  <el-option v-for="dict in present_illness" :key="dict.value" :label="dict.label"
                    :value="dict.label" />
                </el-select>
      </el-form-item>
              <!-- {{ medicalForm.presentIllness }} -->
            </el-col>
            <el-col :span="12">
              <!-- <el-form-item label="既往史" prop="pastHistory">
                <el-select v-model="medicalForm.pastHistory" multiple placeholder="请选择" style="width: 100%">
                  <el-option v-for="item in pastHistoryOptions" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item> -->

              <el-form-item label="现病史" prop="pastHistory">
                <el-select v-model="medicalForm.pastHistory" multiple placeholder="请选择现病史" value-key="label">
                  <el-option v-for="dict in medical_history" :key="dict.value" :label="dict.label"
                    :value="dict.label" />
                </el-select>
      </el-form-item>
              <!-- {{ medicalForm.pastHistory }} -->
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <!-- <el-form-item label="过敏史" prop="allergyHistory">
                <el-select v-model="medicalForm.allergyHistory" multiple placeholder="请选择" style="width: 100%">
                  <el-option v-for="item in allergyHistoryOptions" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item> -->

              <el-form-item label="过敏史" prop="allergyHistory">
                <el-select v-model="medicalForm.allergyHistory" multiple placeholder="请选择现病史" value-key="label">
                  <el-option v-for="dict in allergic_history" :key="dict.value" :label="dict.label"
                    :value="dict.label" />
                </el-select>
      </el-form-item>
              <!-- {{ medicalForm.allergyHistory }} -->
            </el-col>
            <el-col :span="12">
              <!-- <el-form-item label="个人史" prop="personalHistory">
                <el-select v-model="medicalForm.personalHistory" multiple placeholder="请选择" style="width: 100%">
                  <el-option v-for="item in personalHistoryOptions" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item> -->
              <el-form-item label="个人史" prop="personalHistory">
                <el-select v-model="medicalForm.personalHistory" multiple placeholder="请选择现病史" value-key="label">
                  <el-option v-for="dict in personal_history" :key="dict.value" :label="dict.label"
                    :value="dict.label" />
                </el-select>
      </el-form-item>
              <!-- {{ medicalForm.personalHistory  }} -->
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <!-- <el-form-item label="家族史" prop="familyHistory">
                <el-select v-model="medicalForm.familyHistory" multiple placeholder="请选择" style="width: 100%">
                  <el-option v-for="item in familyHistoryOptions" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item> -->
              <el-form-item label="家族史" prop="familyHistory">
                <el-select v-model="medicalForm.familyHistory" multiple placeholder="请选择现病史" value-key="label">
                  <el-option v-for="dict in family_history" :key="dict.value" :label="dict.label" :value="dict.label" />
                </el-select>
              </el-form-item>
              <!-- {{ medicalForm.familyHistory   }} -->
      </el-col>
            <el-col :span="12">
              <!-- <el-form-item label="辅助检查" prop="auxiliaryExam">
                <el-select v-model="medicalForm.auxiliaryExam" multiple placeholder="请选择" style="width: 100%">
                  <el-option v-for="item in auxiliaryExamOptions" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item> -->
              <el-form-item label="辅助检查" prop="auxiliaryExam">
                <el-select v-model="medicalForm.auxiliaryExam" multiple placeholder="请选择现病史" value-key="label">
                  <el-option v-for="dict in auxiliary_examination" :key="dict.value" :label="dict.label"
                    :value="dict.label" />
                </el-select>
              </el-form-item>
              <!-- {{ medicalForm.auxiliaryExam      }} -->
      </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="治疗意见" prop="treatmentAdvice">
                <el-input type="textarea" v-model="medicalForm.treatmentAdvice" rows="4" />
              </el-form-item>
      </el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="remarks">
                <el-input type="textarea" v-model="medicalForm.remarks" rows="4" />
              </el-form-item>
      </el-col>
          </el-row>

          <!-- 底部按钮 -->
          <!-- <el-row justify="end" class="mt20">
            <el-button @click="goBack">返回病历</el-button>
            <el-button @click="printRecord">打印病历</el-button>
            <el-button @click="viewHistory">历史病历</el-button>
            <el-button type="primary" @click="saveMedicalRecord">保存</el-button>
            <el-button type="warning" @click="temporarySave">暂存并返回</el-button>
          </el-row> -->
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="西药" name="prescription">
        <!-- 处方表单 -->
        <div class="prescription-container">
          <!-- <div class="prescription-header">
            <el-button size="small">添加药方</el-button>
            <el-button size="small" type="primary">西药药品方1</el-button>
          </div> -->

          <!-- 诊断和医嘱信息 -->
          <el-row :gutter="20" class="mb20">
            <!-- <el-col :span="12">
              <el-form-item label="诊断" prop="diagnosis">
                <el-input type="textarea" v-model="prescriptionForm.diagnosis" />
              </el-form-item>
            </el-col> -->

            <el-form-item label="诊断" prop="diagnosis">
                <el-select v-model="prescriptionForm.diagnosis" multiple placeholder="请选择诊断" value-key="label" style="width: 300px;">
                  <el-option v-for="dict in doctor_diagnosis" :key="dict.value" :label="dict.label"
                    :value="dict.label" />
                </el-select>
              </el-form-item>


            <!-- <el-col :span="12">
              <el-form-item label="医嘱" prop="advice">
                <el-input type="textarea" v-model="prescriptionForm.advice" />
              </el-form-item>
            </el-col> -->

            <el-form-item label="医嘱" prop="advice">
                <el-select v-model="prescriptionForm.advice" multiple placeholder="请选择诊断" value-key="label" style="width: 300px;">
                  <el-option v-for="dict in doctor_order" :key="dict.value" :label="dict.label"
                    :value="dict.label" />
                </el-select>
              </el-form-item>
    </el-row>

          <div class="prescription-content">
            <!-- 左侧药品列表 -->
            <div class="prescription-left">
              <div class="rp-header">
                <span class="rp-title">处方</span>
                <!-- <el-button type="text" icon="Setting">批量设置</el-button> -->
              </div>
              <el-table :data="selectedMedicines" style="width: 100%">
                <!-- <el-table-column type="selection" width="50" /> -->
                <!-- <el-table-column label="序号" type="index" width="50" /> -->
                <el-table-column label="名称" prop="drugGenericName" width="100" />
                <el-table-column label="数量" width="200">
                  <template #default="scope">
                    <el-input-number v-model="scope.row.quantity" :min="1" size="small"
                      @change="handleQuantityChange(scope.row)" />
                  </template>
                </el-table-column>
                <el-table-column label="价格" prop="purchasePrice" width="80">
                  <template #default="{ row }">
                    {{ row.purchasePrice }}元
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
        <template #default="scope">
                    <el-button type="danger" size="small" @click="deleteMedicine(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
              <!-- 附加费用表格 -->
              <div class="additional-fee-table">
                <div class="table-title">附加费用</div>
                <el-table :data="selectedAdditionalFees" style="width: 100%">
                  <el-table-column label="名称" prop="name" width="100" />
                  <el-table-column label="价格" prop="money" width="100">
                    <template #default="{ row }">
                      {{ row.money }}元
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="80">
                    <template #default="scope">
                      <el-button type="danger" size="small" @click="deleteAdditionalFee(scope.$index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <!-- 检查项目表格 -->
              <div class="examination-table">
                <div class="table-title">检查项目</div>
                <el-table :data="selectedExaminations" style="width: 100%">
                  <el-table-column label="名称" prop="projectName" width="100" />
                  <el-table-column label="价格" prop="retailPrice" width="80">
                    <template #default="{ row }">
                      {{ row.retailPrice }}元
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="80">
                    <template #default="scope">
                      <el-button type="danger" size="small" @click="deleteExamination(scope.$index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <!-- 附加费用部分 -->
              <div class="additional-fee">
                <el-button type="success" icon="Plus" @click="showAdditionalFeeDialog">附加费用</el-button>
                <el-button type="success" icon="Plus" @click="showExaminationDialog">检查项目</el-button>
                <el-button type="primary" disabled>{{ user.userName + "医生" }}</el-button>
                <el-button type="primary" disabled>{{ dept.deptName }}</el-button>
                <div class="fee-info">
                  <span>此方合计: {{ totalAmount }} 元</span>
                  <span>共计: {{ endTotalAmount }} 元</span>
                </div>
              </div>
            </div>

            <!-- 右侧搜索 -->
            <div class="prescription-right">
              <div class="search-header">
                <span>药品</span>
                <!-- <el-select v-model="searchForm.type" placeholder="选择类型" @change="handleTypeChange">
                  <el-option label="药品" value="medicine" />
                  <el-option label="项目检查" value="examination" />
                </el-select> -->
                <el-input v-model="searchForm.keyword"
                  :placeholder="searchForm.type === 'medicine' ? '输入药品中文或拼音搜索' : '输入检查项目搜索'" clearable />
                <el-button type="primary" @click="handleSearch">搜索</el-button>
              </div>
              <el-table :data="medicineList" style="width: 100%" height="400">
                <!-- <el-table-column type="selection" width="50" /> -->
                <el-table-column label="名称" prop="drugGenericName" />
                <el-table-column label="规格" prop="drugSpecification" width="100"
                  v-if="searchForm.type === 'medicine'" />
                <!-- <el-table-column label="库存" prop="stock" width="80" v-if="searchForm.type === 'medicine'" /> -->
                <!-- <el-table-column label="价格" prop="purchasePrice" width="80" /> -->
                <el-table-column label="价格" prop="purchasePrice">
                  <template #default="{ row }">
                    {{ row.retailPrice }}元
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                  <template #default="scope">
                    <el-button type="primary" size="small" @click="addMedicine(scope.row)">添加</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>

          <!-- 底部按钮 -->
          <div class="prescription-footer">
            <!-- <el-button icon="goBack">返回病历</el-button> -->
            <!-- <el-button icon="Document">暂存病历</el-button> -->
            <el-button icon="Printer">打印处方</el-button>
            <!-- <el-button icon="List">历史病历</el-button> -->
            <el-button type="primary" icon="Check" @click="savePrescription">保存</el-button>
            <!-- <el-button type="warning" icon="Timer">暂存并返回</el-button> -->
          </div>
        </div>

        <!-- 附加费用弹窗 -->
        <el-dialog v-model="additionalFeeVisible" title="附加费用" width="500px">
          <div class="fee-dialog-content">
            <div class="fee-dialog-header">
              <span>名称与金额设置（勾选需要添加的项目）</span>
            </div>
            <el-table :data="additionalFees" style="width: 100%" @selection-change="handleSelectionChange"
              ref="additionalFeeTableRef">
              <el-table-column type="selection" width="50" />
              <!-- <el-table-column label="序号" type="index" width="60" /> -->
              <el-table-column label="名称" prop="name" />
              <!-- <el-table-column label="数量" width="100">
                <template #default="scope">
                  <el-input-number v-model="scope.row.amount" :min="1" size="small"
                    @change="handleAmountChange(scope.row)" />
                </template>
              </el-table-column> -->
              <el-table-column label="价格" prop="money">
                <template #default="{ row }">
                  {{ row.money }}元
                </template>
              </el-table-column>
              <!-- <el-table-column label="价格" width="100">
                <template #default="scope">
                  <el-input-number v-model="scope.row.price" :min="0" :precision="2" size="small"
                    @change="handlePriceChange(scope.row)" />
                </template>
              </el-table-column> -->
            </el-table>
          </div>
          <template #footer>
            <el-button @click="additionalFeeVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmAdditionalFee">确定</el-button>
          </template>
        </el-dialog>

        <!-- 检查项目弹窗 -->
        <el-dialog v-model="examinationVisible" title="检查项目" width="500px">
          <div class="examination-dialog-content">
            <div class="examination-dialog-header">
              <span>名称与金额设置（勾选需要添加的项目）</span>
            </div>
            <el-table :data="examinations" style="width: 100%" @selection-change="handleExaminationSelectionChange"
              ref="examinationTableRef">
              <el-table-column type="selection" width="50" />
              <el-table-column label="名称" prop="projectName" />
              <el-table-column label="价格" prop="retailPrice">
                <template #default="{ row }">
                  {{ row.retailPrice }}元
                </template>
              </el-table-column>
            </el-table>
          </div>
          <template #footer>
            <el-button @click="examinationVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmExamination">确定</el-button>
      </template>
    </el-dialog>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup name="Diagnosis">
import { getPatient } from "@/api/chy/patient";
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { onMounted } from 'vue';
import { listUser } from "@/api/system/user";
import { listDept } from "@/api/system/dept";
import { listDrug, getDrug, delDrug, addDrug, updateDrug } from "@/api/drug/drug";
import { listFee } from "@/api/system/fee";
import { listProject, getProject, delProject, addProject, updateProject } from "@/api/system/project";
import axios from "axios";
import { addMyData } from "@/api/diagnosis/diagnosis";
import { ElMessage } from "element-plus";

//获取字典数据
const { proxy } = getCurrentInstance();
const { doctor_complaints_info, present_illness, medical_history, allergic_history, personal_history, family_history, auxiliary_examination, sys_user_sex,doctor_diagnosis,doctor_order } = proxy.useDict('doctor_complaints_info', 'present_illness', 'medical_history', 'allergic_history', 'personal_history', 'family_history', 'auxiliary_examination', 'sys_user_sex','doctor_diagnosis','doctor_order');
//附加费用列表
const feeList = ref([]);

const activeTab = ref('medical')
//医生信息
const userList = ref([]);
// 患者信息
const patient = ref({})
//部门列表
const deptList = ref([]);
//工作台 路由传递过来的数据
const route = useRoute();
// const f = route.query.data
const rowData = JSON.parse(route.query.data);
// console.log('路由参数:', rowData);
// console.log(rowData.patientId);
//当前医生信息
const user = ref({})
//当前医生部门信息
const dept = ref({})
// 药品列表
const medicineList = ref([]);

//折扣
const discount = ref(1);


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    drugGenericName: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);


//向后端发送请求保存药品、检查项目、附加费用（处方信息保存）
function savePrescription(){
  //选中药品数据
  const MySelectedMedicines = selectedMedicines.value;
  // console.log(MySelectedMedicines);
  //遍历药品数据只保存药品id和数量
  const MySelectedMedicinesIdAndQuantity = MySelectedMedicines.map(item => ({
    drugId: item.id,
    quantity: item.quantity,
  }));
  // console.log(MySelectedMedicinesIdAndQuantity);
  //检查项目数据
  const MySelectedExaminations = selectedExaminations.value;
  // console.log(MySelectedExaminations);
  //遍历检查项目数据只保存检查项目id
  const MySelectedExaminationsId = MySelectedExaminations.map(item => ({
    projectId: item.projectId,
  }));
  // console.log(MySelectedExaminationsId);
  //附加费用数据
  const MySelectedAdditionalFees = selectedAdditionalFees.value;
  // console.log(MySelectedAdditionalFees);
  //遍历附加费用数据只保存附加费用id
  const MySelectedAdditionalFeesId = MySelectedAdditionalFees.map(item => ({
    feeId: item.id,
  }));
  // console.log(MySelectedAdditionalFeesId);
  //患者信息
  const MyPatient = patient.value;
  // console.log(MyPatient);
  //医生信息
  const MyUser = user.value;
  // console.log(MyUser);
  //医生部门信息
  const MyDept = dept.value;
  // console.log(MyDept);
  //病历信息
  const MyMedicalForm = medicalForm;
  // console.log(MyMedicalForm);
  //处方信息
  const MyPrescriptionForm = prescriptionForm;
  //挂号单号id
  const MyPrescriptionFormId = rowData.id;
  //最终总价信息
  const MyEndTotalAmount = endTotalAmount.value;
  // console.log(MyPrescriptionForm);
  //将数据整合为一个对象
  const MyData = {
    //药品信息
    MySelectedMedicinesIdAndQuantity,
    //检查项目信息
    MySelectedExaminationsId,
    //附加费用信息
    MySelectedAdditionalFeesId,
    //患者信息
    MyPatient,
    //医生信息
    MyUser,
    //医生部门信息
    MyDept,
    //病历信息
    MyMedicalForm,
    //处方信息
    MyPrescriptionForm,
    //挂号单号id
    MyPrescriptionFormId,
    //最终总价信息
    MyEndTotalAmount
  };
  // console.log(MyData);
  // axios.post('http://localhost:8080/work/work/savePrescription', MyData).then(response => {
    
  // })
  addMyData(MyData).then(response => {
    // console.log(response);
    // console.log(response.code);
    if(response.code == 200){
      ElMessage.success('保存成功');
    }else{
      ElMessage.error('保存失败');
    }
  });
}


/** 查询药品信息列表 */
function getDrugList() {
  listDrug(queryParams.value).then(response => {
    // 清空之前先保存临时数组
    const tempList = [];
    response.rows.forEach(item => {
      if (item.drugInventory > 0 && item.drugStatus == '启用') {
        tempList.push(item);
      }
    });
    // 一次性更新 medicineList
    medicineList.value = tempList;
  });
}

/** 查询药品信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreationTime && '' != daterangeCreationTime) {
    queryParams.value.params["beginCreationTime"] = daterangeCreationTime.value[0];
    queryParams.value.params["endCreationTime"] = daterangeCreationTime.value[1];
  }
  listDrug(queryParams.value).then(response => {
    drugList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}


onMounted(() => {
  getPatientById();
  getDoctorById();
  getDrugList();
  getMoreList();
  getProjectList();
});

// getPatientById();
/** 获取患者信息 */
function getPatientById() {
  getPatient(rowData.patientId).then(response => {
    patient.value = response.data;
    // console.log(patient.value);
    // 初始化病历表单数据
    medicalForm.patientName = patient.value.name;
    medicalForm.patientCard = patient.value.id;
    medicalForm.gender = patient.value.sex;
    medicalForm.birthDate = patient.value.birthday;
    medicalForm.phone = patient.value.phone;
    medicalForm.idCard = patient.value.idNumber;

    medicalForm.address = patient.value.address;
    //判断是否是会员
    if (patient.value.vipType != 0) {
      discount.value = 0.95;
    }

    // console.log(patient.value.sex);
    // console.log(medicalForm.gender);

  });

}

// 获取医生信息
async function getDoctorById() {
  try {
    // 调用异步方法并等待结果  这里查询全部不在单写
    const res = await listUser();

    // 更新数据
    userList.value = res.rows;

    // 打印更新后的 userList 数据
    // console.log(userList.value);
  } catch (error) {
    console.error('Error fetching user list:', error);
  }
  // console.log(userList.value);
  userList.value.forEach(item => {
    if (item.userId === rowData.doctorId) {
      user.value = item;
    }
  });
  // console.log(user.value);
  // console.log(user.value.deptId);
  getDeptList();
}

//查询部门信息
async function getDeptList() {
  try {

    const response = await listDept(); // 等待异步操作完成
    deptList.value = response.data;

  } catch (error) {
    console.error('Error fetching department list:', error);
  }
  // console.log(deptList.value); // 数据加载完成后打印
  // console.log(user.value);
  deptList.value.forEach(item => {
    // console.log(item.deptId);
    // console.log(item.deptId == user.value.deptId);
    if (item.deptId == user.value.deptId) {
      // console.log(item);
      dept.value = item;
    }
  })
  // console.log(dept.value);
}

/** 查询费用设置列表 */
function getMoreList() {

  listFee().then(response => {
    additionalFees.value = response.rows;
    // console.log(additionalFees.value);
  });

}

/** 查询检查项目设置列表 */
function getProjectList() {

  listProject().then(response => {
    examinations.value = response.rows;
    // console.log(examinations.value);
  });
}






// 病历表单数据
const medicalFormRef = ref()
const medicalForm = reactive({
  patientName: '',
  patientCard: '',
  gender: '',
  birthDate: '',
  phone: '',
  idCard: '',
  reportType: '',
  address: '',
  // 体格信息
  temperature: '',
  breathing: '',
  pulse: '',
  bloodPressure: '',
  height: '',
  weight: '',
  bloodSugar: '',
  bloodFat: '',
  // 病历信息
  onsetDate: '',
  mainComplaint: [],
  presentIllness: [],
  pastHistory: [],
  allergyHistory: [],
  personalHistory: [],
  familyHistory: [],
  auxiliaryExam: [],
  treatmentAdvice: '',
  remarks: ''
})

// 病历选项数据
const mainComplaintOptions = ref([
  { label: '头痛', value: 'headache' },
  { label: '发热', value: 'fever' },
  { label: '咳嗽', value: 'cough' }
])

const presentIllnessOptions = ref([
  { label: '急性发作', value: 'acute' },
  { label: '慢性发作', value: 'chronic' }
])

const pastHistoryOptions = ref([
  { label: '高血压', value: 'hypertension' },
  { label: '糖尿病', value: 'diabetes' }
])

const allergyHistoryOptions = ref([
  { label: '青霉素过敏', value: 'penicillin' },
  { label: '海鲜过敏', value: 'seafood' }
])

const personalHistoryOptions = ref([
  { label: '吸烟', value: 'smoking' },
  { label: '饮酒', value: 'drinking' }
])

const familyHistoryOptions = ref([
  { label: '父母高血压', value: 'parents_hypertension' },
  { label: '家族糖尿病史', value: 'family_diabetes' }
])

const auxiliaryExamOptions = ref([
  { label: '血常规', value: 'blood_routine' },
  { label: 'B超', value: 'ultrasound' }
])

// 处方相关数据
const prescriptionForm = reactive({
  doctor: '',
  department: '',
  medicines: [],
  diagnosis: '',
  advice: ''
})

// 选中的药品列表
const selectedMedicines = ref([])

// 选中的附加费用列表
const selectedAdditionalFees = ref([])

// 搜索表单
const searchForm = reactive({
  type: 'medicine',
  keyword: ''
})

// 药品列表数据
// const medicineList = ref([
//   { name: '止咳糖浆', specification: '1g*1', stock: 1000, price: 0.08 },
//   { name: '止咳露剂明目片', specification: '1g*1', stock: 1000, price: 0.16 },
//   { name: '滴眼液复合维生素', specification: '1g*1', stock: 1000, price: 0.15 }
// ])

// 检查项目列表
const examinationList = ref([
  { name: 'B超检查', price: 200 },
  { name: 'CT检查', price: 500 },
  { name: '血常规', price: 50 }
])

// 搜索结果列表
const searchResultList = computed(() => {
  return searchForm.type === 'medicine' ? medicineList.value : examinationList.value
  const list = searchForm.type === 'medicine' ? medicineList.value : examinationList.value
  if (!searchForm.keyword) {
    return list
  }
  return list.filter(item => {
    return item.name.toLowerCase().includes(searchForm.keyword.toLowerCase())
  })
})

// 附加费用弹窗
const additionalFeeVisible = ref(false)
const additionalFeeTableRef = ref()
const additionalFees = ref([
  { name: '注射费', amount: 1, price: 3.00, selected: false },
  { name: '材料费', amount: 1, price: 4.00, selected: false },
  { name: '处置费', amount: 1, price: 6.00, selected: false },
  { name: '治疗费', amount: 1, price: 8.00, selected: false }
])

// 检查项目相关数据
const examinationVisible = ref(false)
const examinationTableRef = ref()
const examinations = ref([
  { name: '血常规', price: 30.00, selected: false },
  { name: '尿常规', price: 20.00, selected: false },
  { name: 'B超', price: 100.00, selected: false },
  { name: 'CT', price: 200.00, selected: false }
])

// 选中的检查项目列表
const selectedExaminations = ref([])

// 计算属性
const totalAmount = computed(() => {
  const medicineAmount = selectedMedicines.value.reduce((sum, medicine) => {
    return sum + (Number(medicine.purchasePrice) * Number(medicine.quantity || 1))
  }, 0)
  const feeAmount = selectedAdditionalFees.value.reduce((sum, fee) => sum + Number(fee.money || 0), 0)
  const examAmount = selectedExaminations.value.reduce((sum, exam) => sum + Number(exam.retailPrice || 0), 0)
  return (medicineAmount + feeAmount + examAmount).toFixed(2)
})

//最终价格
const endTotalAmount = computed(() => {
  const medicineAmount = selectedMedicines.value.reduce((sum, medicine) => {
    return sum + (Number(medicine.purchasePrice) * Number(medicine.quantity || 1))
  }, 0)
  const feeAmount = selectedAdditionalFees.value.reduce((sum, fee) => sum + Number(fee.money || 0), 0)
  const examAmount = selectedExaminations.value.reduce((sum, exam) => sum + Number(exam.retailPrice || 0), 0)
  return ((medicineAmount + feeAmount + examAmount)*0.95).toFixed(2)
})




// 方法
const handleTypeChange = () => {
  searchForm.keyword = ''
}

const handleSearch = () => {
  // 设置搜索关键词
  data.queryParams.drugGenericName = searchForm.keyword;
  // 执行搜索
  getDrugList();
}

const goBack = () => {
  router.go(-1)
}

const printRecord = () => {
  // TODO: 实现打印功能
}

const viewHistory = () => {
  // TODO: 实现查看历史病历功能
}

const saveMedicalRecord = () => {
  // TODO: 实现保存病历功能
}

const temporarySave = () => {
  // TODO: 实现暂存功能
}

const editMedicine = (row) => {
  // TODO: 实现编辑药品功能
}

const showAdditionalFeeDialog = () => {
  // 重置选中状态
  additionalFees.value.forEach(fee => {
    fee.selected = false
  })
  additionalFeeVisible.value = true
}

const handleSelectionChange = (selection) => {
  // 更新选中状态
  additionalFees.value.forEach(fee => {
    fee.selected = selection.some(item => item.name === fee.name)
  })
}

const handleAmountChange = (row) => {
  // 如果该费用项已选中，更新表格中的数量
  if (row.selected) {
    const index = selectedAdditionalFees.value.findIndex(item => item.name === row.name)
    if (index !== -1) {
      selectedAdditionalFees.value[index].amount = row.amount
      selectedAdditionalFees.value[index].subtotal = (row.amount * row.price).toFixed(2)
    }
  }
}

const handlePriceChange = (row) => {
  // 如果该费用项已选中，更新表格中的价格
  if (row.selected) {
    const index = selectedAdditionalFees.value.findIndex(item => item.name === row.name)
    if (index !== -1) {
      selectedAdditionalFees.value[index].price = row.price
      selectedAdditionalFees.value[index].subtotal = (row.amount * row.price).toFixed(2)
    }
  }
}

const confirmAdditionalFee = () => {
  // 获取选中的费用项
  const selectedFees = additionalFees.value.filter(fee => fee.selected)

  // 更新选中的费用列表
  selectedAdditionalFees.value = selectedFees.map(fee => ({
    ...fee,
    subtotal: (fee.amount * fee.price).toFixed(2)
  }))

  additionalFeeVisible.value = false
}

const deleteAdditionalFee = (index) => {
  selectedAdditionalFees.value.splice(index, 1)
  // 同步更新弹窗中的选中状态
  const deletedFee = selectedAdditionalFees.value[index]
  if (deletedFee) {
    const fee = additionalFees.value.find(item => item.name === deletedFee.name)
    if (fee) {
      fee.selected = false
    }
  }
}

// const savePrescription = () => {
//   // TODO: 实现暂存处方功能
// }

const submitPrescription = () => {
  // TODO: 实现提交处方功能
}

const handleQuantityChange = (row) => {
  // 通过drugId和drugGenericName双重判断确保正确找到要修改的药品
  const index = selectedMedicines.value.findIndex(item =>
    item.drugId === row.drugId && item.drugGenericName === row.drugGenericName
  );

  if (index !== -1) {
    const updatedMedicine = { ...selectedMedicines.value[index], quantity: row.quantity };
    selectedMedicines.value.splice(index, 1, updatedMedicine);
  }
}

const addMedicine = (item) => {
  // 检查药品是否已经存在（通过drugId和drugGenericName双重判断）
  const existingIndex = selectedMedicines.value.findIndex(medicine =>
    medicine.drugId === item.drugId && medicine.drugGenericName === item.drugGenericName
  );

  if (existingIndex !== -1) {
    // 如果完全相同的药品已存在，增加数量
    const updatedMedicine = {
      ...selectedMedicines.value[existingIndex],
      quantity: (selectedMedicines.value[existingIndex].quantity || 1) + 1
    };
    selectedMedicines.value.splice(existingIndex, 1, updatedMedicine);
      } else {
    // 如果是新的药品，添加新项
    const newItem = {
      ...item,
      quantity: 1
    };
    selectedMedicines.value.push(newItem);
  }
}

const deleteMedicine = (index) => {
  selectedMedicines.value.splice(index, 1);
}

const showExaminationDialog = () => {
  // 重置选中状态
  examinations.value.forEach(exam => {
    exam.selected = false
  })
  // 设置已选项目的选中状态
  selectedExaminations.value.forEach(selectedExam => {
    const exam = examinations.value.find(item => item.projectName === selectedExam.projectName)
    if (exam) {
      exam.selected = true
    }
  })
  examinationVisible.value = true
}

const handleExaminationSelectionChange = (selection) => {
  // 更新选中状态
  examinations.value.forEach(exam => {
    exam.selected = selection.some(item => item.projectName === exam.projectName)
  })
}

const confirmExamination = () => {
  // 获取选中的检查项目
  const selectedExams = examinations.value.filter(exam => exam.selected)

  // 更新选中的检查项目列表
  selectedExaminations.value = selectedExams.map(exam => ({
    projectName: exam.projectName,
    retailPrice: exam.retailPrice,
    projectId: exam.id,
  }))
  // console.log(selectedExaminations.value);

  examinationVisible.value = false
}

const deleteExamination = (index) => {
  selectedExaminations.value.splice(index, 1)
  // 同步更新弹窗中的选中状态
  const deletedExam = selectedExaminations.value[index]
  if (deletedExam) {
    const exam = examinations.value.find(item => item.projectName === deletedExam.projectName)
    if (exam) {
      exam.selected = false
    }
  }
}

</script>

<style scoped>
.prescription-container {
  padding: 20px;
}

.prescription-header {
  margin-bottom: 20px;
}

.prescription-content {
  display: flex;
  gap: 20px;
}

.prescription-left {
  flex: 0 0 60%;
  /* 左侧固定60%宽度 */
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 20px;
}

.prescription-right {
  flex: 0 0 calc(40% - 20px);
  /* 右侧固定40%宽度，减去gap的20px */
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 20px;
}

.rp-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.rp-title {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}

.search-header {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-header .el-select {
  width: 120px;
}

.search-header .el-input {
  flex: 1;
}

.additional-fee {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #dcdfe6;
}

.fee-info {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
}

.fee-dialog-header {
  margin-bottom: 20px;
}

.sub-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0;
  padding-left: 10px;
  border-left: 4px solid #409EFF;
}

.mt20 {
  margin-top: 20px;
}

.mb20 {
  margin-bottom: 20px;
}

.additional-fee-table {
  margin-top: 20px;
  border-top: 1px solid #dcdfe6;
  padding-top: 20px;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.examination-table {
  margin-top: 20px;
  border-top: 1px solid #dcdfe6;
  padding-top: 20px;
}
</style>
